package cn.iune.backcenter.authen;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSONObject;
import com.justep.baas.Utils;
import com.justep.baas.data.DataUtils;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

import cn.iune.common.base.BaseJPAImpl;



@Repository
public class SaRelationalLoginDaoJPAImpl extends BaseJPAImpl<SaRelationalLogin> implements ISaRelationalLoginDao {

//	private final Logger log = LoggerFactory.getLogger(SaRelationalLoginDaoJPAImpl.class);

	private String kSql;
	
//	@PersistenceContext 
//	private EntityManager em ;
	
	@Override
	public void insert(SaRelationalLogin fc) {
		em.persist(fc);
	}

	@Override
	public void delete(String fID) {
		em.remove(em.getReference(SaRelationalLogin.class, fID));
	}

	@Override
	public SaRelationalLogin update(SaRelationalLogin fc) {
		SaRelationalLogin objNew = em.merge(fc);
		return objNew;
	}

	@Override
	public List<SaRelationalLogin> getAll() {
		kSql="SELECT SaRelationalLogin FROM SaRelationalLogin SaRelationalLogin ";
		Query query = em.createQuery(kSql);
		@SuppressWarnings("unchecked")
		List<SaRelationalLogin> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public SaRelationalLogin getByID(String fID) {
		SaRelationalLogin singleResult = em.find(SaRelationalLogin.class, fID);
		return singleResult;
	}

	
	@Override
	public JSONObject create(JSONObject data) {
		//缺省列
		String defColstr = Utils.getDefCols(SaRelationalLogin.class);
		data.put("defColstr", defColstr);
		return Utils.newData(data);
	}
	
	
	
	@Override
	public JSONObject query(JSONObject data) throws SQLException {
		
		// 获取参数
		JSONObject columns = data.getJSONObject("columns"); // 列定义
		//System.out.println("SaRelationalLoginDaoJPAImpl.query.columns-->>"+columns.toJSONString());
		//删除指定键值，不允许查询密码列
		columns.remove("sPassword");
		
		String orderBy = data.getString("orderBy"); // 排序
		Integer limit = data.getInteger("limit"); // 分页查询的行数
		Integer offset = data.getInteger("offset"); // 分页查询的行偏移
		String search = data.getString("search"); // 检索关键字
		String filter = data.getString("filter"); // 过滤条件
		String id = data.getString("id");

		String format = "SELECT %s FROM %s %s %s ";
//		String format = "SELECT ShopCart FROM ShopCart ShopCart %s %s ";
		String select = "SaRelationalLogin.*";
		String from = "SaRelationalLogin SaRelationalLogin";
		
		String where = "";

		
		// 存放SQL中的参数值
		List<Object> sqlParams = new ArrayList<Object>();
		// 存放SQL中的过滤条件
		List<String> filters = new ArrayList<String>();
		
		if (Utils.isNotEmptyString(search)) {
			// 增加过滤条件
			filters.add("sCode LIKE ? OR sName LIKE ? OR sLoginName LIKE ? OR sMail LIKE ? OR sMobilePhone LIKE ?");
			// 检索关键字中如果没有%，则前后自动加%
			search = (search.indexOf("%") != -1) ? search : "%" + search + "%";
			// sqlParams的参数个数和顺序必须与过滤条件的?相匹配 
			for (int i = 0; i < 5; i++) {
				sqlParams.add(search);
			}
		}
		
		//处理过滤条件
		if (Utils.isNotEmptyString(filter)) {
			filters.add(filter);
		}
		//处理id
		if (Utils.isNotEmptyString(id)) {
			filters.add("sID='"+id+"'");
		}
	
		
		if(filters != null && filters.size() > 0){
			if(where.indexOf("WHERE")== -1){
				//不包含WHERE关键字
				where = "WHERE " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}else{
				//已包含
				where = where + " AND " + DataUtils.arrayJoin(filters.toArray(), "(%s)", " AND ");
			}
		}
		//orderBy = "sortNo ASC";
//		String where = (filters != null && filters.size() > 0) ? " WHERE " + CommonService.arrayJoin(filters.toArray(), "(%s)", " AND ") : "";
		orderBy = Utils.isNotEmptyString(orderBy) ? " ORDER BY " + orderBy : "";
		
		String sql = String.format(format, select, from, where, orderBy);
		System.out.println("sql-->"+sql);
		
//		Connection conn = DataUtils.getConnection(DataUtils.DATASOURCE_1);
		Connection conn = super.getConnection();
		String sqlTotal = String.format(format, "COUNT(*)", from, where, "");
		Object total = DataUtils.getValueBySQL(conn, sqlTotal, sqlParams);
		//SELECT ShopCart.fID FROM ShopCart ShopCart    LIMIT 0,-1//为-1时报错。
		if(limit==-1){
			limit = Integer.parseInt(total.toString());
		}
		
//		Table table = DataUtils.queryData(conn, tableName, columns, filters, orderBy, params, offset, limit);
		Table table = DataUtils.queryData(conn, sql, sqlParams, columns, offset, limit);
		//关闭连接
		conn.close();

		table.setTotal(Integer.parseInt(total.toString()));
		JSONObject json = Transform.tableToJson(table);
		
		return json;
	}

	@Override
	public SaRelationalLogin getByNo(String identification) {
		System.out.println("通过identification查询人员对象！");
		// TODO Auto-generated method stub
		kSql="SELECT SaRelationalLogin FROM SaRelationalLogin SaRelationalLogin "
				+ " WHERE SaRelationalLogin.identification = :identification";
		Query query = em.createQuery(kSql);
		query.setParameter("identification", identification);
		
		SaRelationalLogin singleResult = null;
		try {
			singleResult = (SaRelationalLogin) query.getSingleResult();
		} catch (NoResultException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			System.out.println("e.getMessage()-->"+e.getMessage());
			//No entity found for query
			if("No entity found for query".equals(e.getMessage())){
				return null;
			}
		}
		
		return singleResult;
	}

	@Override
	public SaRelationalLogin getPhone(String personID) {
		// TODO Auto-generated method stub
		kSql="SELECT SaRelationalLogin FROM SaRelationalLogin SaRelationalLogin "
				+ " WHERE SaRelationalLogin.sType = 'PHONE'"
				+ " AND SaRelationalLogin.personID = :personID";
		Query query = em.createQuery(kSql);
		query.setParameter("personID", personID);
		
		SaRelationalLogin singleResult = null;
		try {
			singleResult = (SaRelationalLogin) query.getSingleResult();
		} catch (NoResultException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			System.out.println("e.getMessage()-->"+e.getMessage());
			//No entity found for query
			if("No entity found for query".equals(e.getMessage())){
				return null;
			}
		}
		
		return singleResult;
	}



}
